<template>
  <ContentWrap>
    <el-row :gutter="16" class="device-data-row">
      <!-- 设备数 -->
      <el-col :lg="4" :md="6" :sm="12" :xs="24">
        <SummaryCard
          title="设备数"
          tooltip="系统中注册的设备总数量"
          icon="ep:monitor"
          icon-color="text-blue-500"
          icon-bg-color="bg-blue-100"
          :value="statisticsInfo.totalCount"
          :decimals="0"
        />
      </el-col>

      <!-- 在线 -->
      <el-col :lg="4" :md="6" :sm="12" :xs="24">
        <SummaryCard
          title="在线"
          tooltip="当前在线的设备数量"
          icon="ep:connection"
          icon-color="text-green-500"
          icon-bg-color="bg-green-100"
          :value="statisticsInfo.onlineCount"
          :decimals="0"
        />
      </el-col>

      <!-- 离线 -->
      <el-col :lg="4" :md="6" :sm="12" :xs="24">
        <SummaryCard
          title="离线"
          tooltip="当前离线的设备数量"
          icon="ep:remove"
          icon-color="text-red-500"
          icon-bg-color="bg-red-100"
          :value="statisticsInfo.offlineCount"
          :decimals="0"
        />
      </el-col>

      <!-- 昨日订单 -->
      <el-col :lg="4" :md="6" :sm="12" :xs="24">
        <SummaryCard
          title="昨日订单"
          tooltip="昨天产生的订单数量"
          icon="ep:document"
          icon-color="text-purple-500"
          icon-bg-color="bg-purple-100"
          :value="statisticsInfo.yesterdayOrderCount"
          :decimals="0"
        />
      </el-col>

      <!-- 全部订单 -->
      <el-col :lg="4" :md="6" :sm="12" :xs="24">
        <SummaryCard
          title="全部订单"
          tooltip="所有订单的总数量"
          icon="ep:tickets"
          icon-color="text-orange-500"
          icon-bg-color="bg-orange-100"
          :value="statisticsInfo.totalOrderCount"
          :decimals="0"
        />
      </el-col>

      <!-- 累计使用时间 -->
      <el-col :lg="4" :md="6" :sm="12" :xs="24">
        <SummaryCard
          title="累计使用时间"
          tooltip="所有设备的累计使用时长"
          icon="ep:timer"
          icon-color="text-cyan-500"
          icon-bg-color="bg-cyan-100"
          :value="statisticsInfo.totalDuration"
          :decimals="0"
          prefix=""
        />
      </el-col>
    </el-row>
  </ContentWrap>
  <ContentWrap>
    <el-form :inline="true" :model="queryParams" label-width="120px">
      <el-form-item label="设备唯一编码">
        <el-input
          v-model="queryParams.serialNumber"
          class="!w-240px"
          placeholder="请输入设备唯一编码"
        />
      </el-form-item>
      <el-form-item label="设备名称">
        <el-input v-model="queryParams.deviceName" class="!w-240px" placeholder="请输入设备名称" />
      </el-form-item>
      <el-form-item label="在线状态">
        <el-select v-model="queryParams.state" class="!w-240px" placeholder="请选择">
          <el-option label="在线" :value="0" />
          <el-option label="离线" :value="1" />
          <el-option label="使用中" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属门店">
        <el-select v-model="queryParams.storeId" class="!w-240px" placeholder="请选择">
          <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="注册时间">
        <el-date-picker
          v-model="queryParams.createTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          class="!w-240px"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <!-- 新增设备 -->
        <el-button type="primary" @click="handleAdd">新增设备</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <el-table
      :data="tableData"
      v-loading="loading"
      style="width: 100%"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <el-table-column prop="serialNumber" label="设备号" align="center" />
      <el-table-column prop="deviceName" label="设备名称" align="center" />
      <el-table-column prop="state" label="在线状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.state === 1 ? 'danger' : 'success'">{{
            DeviceStateNameEnum[DeviceStateEnum[scope.row.state]]
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="经纬度" align="center">
        <template #default="scope">
          <div>
            <div>经度：{{ scope.row.longitude || '--' }}</div>
            <div>纬度：{{ scope.row.latitude || '--' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="storeId" label="所属门店" align="center">
        <template #default="scope">
          <div>{{ storeList.find((item: any) => item.id === scope.row.storeId)?.name }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="storeContractNumber" label="门店联系方式" align="center" />
      <el-table-column prop="heartbeatTime" label="最近心跳时间" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.heartbeatTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="onlineTime" label="最近上线时间" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.onlineTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="offlineTime" label="最近离线时间" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.offlineTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getDeviceList"
    />
  </ContentWrap>
  <AddDevices
    ref="addDevicesRef"
    v-if="isView"
    @close="isView = false"
    @submit="handleSubmit"
    :editInfo="editInfo"
  />
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, toRefs } from 'vue'
import SummaryCard from '@/components/SummaryCard/index.vue'
import AddDevices from './addDevices.vue'
import { formatDate } from '@/utils/formatTime'
import { SofaBasicApi } from '@/api/application/sofa'
import * as DeliveryPickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore/index'
const queryParams = ref({
  serialNumber: '',
  deviceName: '',
  state: '',
  storeId: '',
  createTime: '',
  pageNo: 1,
  pageSize: 10
})
const isView = ref(false)
const total = ref(0)
const state = reactive({
  storeList: [] as any,
  loading: false as boolean,
  tableData: [] as any,
  statisticsInfo: {
    totalCount: 0,
    onlineCount: 0,
    offlineCount: 0,
    yesterdayOrderCount: 0,
    totalOrderCount: 0,
    totalDuration: 0
  },
  editInfo: {} as any
})
const { storeList, loading, tableData, statisticsInfo, editInfo } = toRefs(state)
const message = useMessage()
enum DeviceStateEnum {
  INACTIVE = 0, //在线
  OFFLINE = 1, //离线
  ONLINE = 2 //使用中
}
enum DeviceStateNameEnum {
  INACTIVE = '在线',
  OFFLINE = '离线',
  ONLINE = '使用中'
}

defineOptions({ name: 'SofaDevices' })

const handleSearch = () => {
  queryParams.value.pageNo = 1
  getDeviceList()
}

const handleReset = () => {
  queryParams.value = {
    serialNumber: '',
    deviceName: '',
    state: '',
    storeId: '',
    createTime: '',
    pageNo: 1,
    pageSize: 10
  }
  getDeviceList()
}
const handleSubmit = async (data: any) => {
  console.log(data)
  if (data.id) {
    await SofaBasicApi.updateSofaBasice(data)
    message.success('修改成功')
  } else {
    await SofaBasicApi.createSofaBasice(data)
    message.success('新增成功')
  }
  isView.value = false
  getDeviceList()
}
const handleAdd = () => {
  console.log('新增设备')
  editInfo.value = {}
  isView.value = true
}
// 获取设备
const getStatisticsInfo = async () => {
  try {
    const data = await SofaBasicApi.getDevicestatistics()
    statisticsInfo.value = data
  } catch (error) {
    console.error('获取设备统计信息失败:', error)
  }
}
// 获取设备列表
const getDeviceList = async () => {
  loading.value = true
  try {
    const res = await SofaBasicApi.getDevicePage({ ...queryParams.value })
    tableData.value = res.list
    total.value = res.total || 0
  } catch (error) {
    console.error('获取设备列表失败:', error)
  } finally {
    loading.value = false
  }
}
// 编辑设备
const handleEdit = (row) => {
  console.log(row)
  editInfo.value = row
  isView.value = true
}
onMounted(() => {
  getStoreList()
  getStatisticsInfo()
  getDeviceList()
})
const getStoreList = async () => {
  const res = await DeliveryPickUpStoreApi.getDeliveryPickUpStorePage({
    pageNo: 1,
    pageSize: 100
  })
  storeList.value = res.list
}
</script>
<style lang="scss" scoped>
.device-data-row {
  .el-col {
    margin-bottom: 16px;
  }
}
</style>
